<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
  <meta name="generator" content=
  "HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org">

  <title>binary_search</title>
  <link href="../cppreference.css" rel="stylesheet" type="text/css">
</head>

<body>
<table>
  <tr>
  <td>
  <div class="body-content">

  <div class="header-box">
    <a href="../index.html">cppreference.com</a> &gt; <a href=
    "index.html">C++ Algorithms</a> &gt; <a href=
    "binary_search.html">binary_search</a>
  </div>

  <div class="name-format">
    binary_search
  </div>

  <div class="syntax-name-format">
    Syntax:
  </div>
  <pre class="syntax-box">
  #include &lt;algorithm&gt;
  bool binary_search( iterator start, iterator end, const <a href=
"../containers.html">TYPE</a>&amp; val );
  bool binary_search( iterator start, iterator end, const <a href=
"../containers.html">TYPE</a>&amp; val, Comp f );
</pre>

  <p>The binary_search() function searches from <em>start</em> to
  <em>end</em> for <em>val</em>. The elements between <em>start</em>
  and <em>end</em> that are searched should be in ascending order as
  defined by the &lt; operator. Note that a binary search <strong>will
  not work</strong> unless the elements being searched are in
  order.</p>

  <p>If <em>val</em> is found, binary_search() returns true, otherwise
  false.</p>

  <p>If the function <em>f</em> is specified, then it is used to
  compare elements.</p>

  <p>For example, the following code uses binary_search() to determine
  if the integers 0-9 are in an array of integers:</p>
  <pre class="example-code">
 int nums[] = { -242, -1, 0, 5, 8, 9, 11 };
 int start = 0;
 int end = 7;           

 for( int i = 0; i &lt; 10; i++ ) {
   if( binary_search( nums+start, nums+end, i ) ) {
     cout &lt;&lt; &quot;nums[] contains &quot; &lt;&lt; i &lt;&lt; endl;
   } else {
     cout &lt;&lt; &quot;nums[] DOES NOT contain &quot; &lt;&lt; i &lt;&lt; endl;
   }
 }              
</pre>

  <p>When run, this code displays the following output:</p>
  <pre class="example-code">
 nums[] contains 0
 nums[] DOES NOT contain 1
 nums[] DOES NOT contain 2
 nums[] DOES NOT contain 3
 nums[] DOES NOT contain 4
 nums[] contains 5
 nums[] DOES NOT contain 6
 nums[] DOES NOT contain 7
 nums[] contains 8
 nums[] contains 9              
</pre>

  <div class="related-name-format">
    Related topics:
  </div>

  <div class="related-content">
    <a href="equal_range.html">equal_range</a><br>
    <a href="is_sorted.html">is_sorted</a><br>
    <a href="lower_bound.html">lower_bound</a><br>
    <a href="partial_sort.html">partial_sort</a><br>
    <a href="partial_sort_copy.html">partial_sort_copy</a><br>
    <a href="sort.html">sort</a><br>
    <a href="stable_sort.html">stable_sort</a><br>
    <a href="upper_bound.html">upper_bound</a>
  </div>
  </div>
  </td>
  


  </tr>
  </table>
</body></html>
